import React        from 'react';

import _mm          from '../../util/Mutil.js';
import _user        from '../../service/userService.js';

import './index.scss';

class Login extends React.Component{
  constructor (props) {
    super(props)
    this.state = {
      username: '',
      password: '',
      redirect: _mm.getUrlParam('redirect') || '/'
    }
  }
  // 生命周期
  componentWillMount () {
    document.title = '登录 - MMALL ADMIN';
  }
  render () {
    return (
      <div className="col-md-4 col-md-offset-4">
        <div className="panel panel-default login-panel">
          <div className="panel-heading">欢迎登录 - MMALL管理系统</div>
          <div className="panel-body">
            <div>
              <div className="form-group">
                <input type="text" name="username" className="form-control" placeholder="请输入用户名"
                  onChange={ (e) => { this.onInputChange(e) } }
                  onKeyUp={e => this.onInputKeyUp(e)}
                 />
              </div>
              <div className="form-group">
                <input type="password" name="password" className="form-control" placeholder="请输入密码"
                  onChange={ (e) => { this.onInputChange(e) } }
                  onKeyUp={e => this.onInputKeyUp(e)}
                />
              </div>
              <button className="btn btn-lg btn-primary btn-block"
                onClick = {(e) => { this.onSubmit() } }
              >登录</button>
            </div>
          </div>
        </div>
      </div>
    )
  }
  // event
  onInputChange (e) {
    let inputName = e.target.name
    let inputVal = e.target.value
    this.setState({
      [inputName]: inputVal
    })
  }
  onInputKeyUp (e) {
    if (e.keyCode === 13) {
      this.onSubmit()
    }
  }
  onSubmit () {
    let loginInfo = {
      username : this.state.username,
      password : this.state.password
    };
    let checkResult = _user.checkLoginInfo(loginInfo)
    // 验证通过
    if(checkResult.status){
      _user.login(loginInfo).then((res) => {
        _mm.setStorage('userInfo', res)
        this.props.history.push(this.state.redirect)
      }, (errMsg) => {
        _mm.errorTips(errMsg);
      })
    }
    // 验证不通过
    else{
        _mm.errorTips(checkResult.msg);
    }
  }
}

export default Login;